/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package BeanView;

import Dao.DaoLastName;
import HibernateUtil.HibernateUtil;
import Pojo.Employees;
import Pojo.Lastname;
import java.util.Arrays;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author olegk
 */
@ManagedBean
@ViewScoped
public class MbVLastName  implements java.io.Serializable{
    private Session session;
    private Transaction transaction;
    private Lastname lastName;
    private List<Lastname> listLastName;
    private List<Lastname> listLastNameFiltered;
    private String newName;
    
    public MbVLastName(){
        this.lastName=new Lastname();
        this.lastName.setId(0L);
        this.newName = "";
    }
    
    public void registration(){
        this.session=null;
        this.transaction=null;
        
        try
        {            
            if(this.newName.trim().equals(""))
            {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ошибка:", "Укажите фамилию"));
                return;
            }
            DaoLastName daoLastName=new DaoLastName();            
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=session.beginTransaction();
            String query = "from Lastname l where lower(l.name)=lower(?)";
            List<Object> param = Arrays.asList((Object)this.newName);
            if(daoLastName.selectLastName(session, query, param)!=null)
            {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ошибка:", "Имя уже зарегистрировано в системе"));
                return;
            }
            this.lastName.setName(newName);           
            daoLastName.register(this.session, this.lastName);            
            this.transaction.commit();            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Успех:", "Регистрация прошла успешно"));
            this.lastName=new Lastname();
            this.lastName.setId(0L);
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }
    
    public List<Lastname> getAll(){
        this.session=null;
        this.transaction=null;        
        try
        {
            DaoLastName daoLastName=new DaoLastName();            
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=this.session.beginTransaction();            
            this.listLastName=daoLastName.getAll(this.session);            
            this.transaction.commit();            
            return this.listLastName;
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));            
            return null;
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }        
    }
    
    public Lastname getId(String id){
        this.session=null;
        this.transaction=null;        
        try
        {
            DaoLastName daoLastName=new DaoLastName();             
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=this.session.beginTransaction();  
            String query = "from Lastname ln where ln.id = ?";
            List<Object> param = Arrays.asList((Object) Long.parseLong(id));
            this.lastName=daoLastName.selectLastName(this.session, query, param);           
            this.transaction.commit();            
            return this.lastName;
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));            
            return null;
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }
    
    public void remove(){
        this.session=null;
        this.transaction=null;        
        try
        {            
            DaoLastName daoLastName=new DaoLastName();
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=session.beginTransaction();                     
            daoLastName.delete(this.session, this.lastName);            
            this.transaction.commit();            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Успех:", "Фамилия удалена"));
            this.lastName=new Lastname();
            this.lastName.setId(0L);
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }

    public void update(){
        this.session=null;
        this.transaction=null;        
        try
        {            
            DaoLastName daoLastName=new DaoLastName();
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=session.beginTransaction();
            String query = "from Lastname l where l.id <> ? and l.name = ?";
            List<Object> param = Arrays.asList((Object)this.lastName.getId(), 
                                (Object)this.lastName.getName());
            if(daoLastName.selectLastName(this.session, query, param)!=null)
            {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ошибка:", "Организация уже зарегистрирована в системе"));
                return;
            }           
            daoLastName.update(this.session, this.lastName);            
            this.transaction.commit();            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Успех:", "Регистрация прошла успешно"));
            this.lastName=new Lastname();
            this.lastName.setId(0L);
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }

    public void setLastNameParent(){
        Object parent=FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("parent");
        if(parent instanceof Employees){
            Employees employees=(Employees)parent;
            employees.setLastname(this.lastName);
        }
        this.lastName=new Lastname();
        this.lastName.setId(0L);
    }

    public String cancel(){
        this.lastName=new Lastname();
        this.lastName.setId(0L);
        return null;
    }
    
    public Lastname getLastName() {
        return lastName;
    }

    public void setLastName(Lastname lastName) {
        this.lastName = lastName;
    }

    public List<Lastname> getListLastName() {
        return listLastName;
    }

    public void setListLastName(List<Lastname> listLastName) {
        this.listLastName = listLastName;
    }

    public List<Lastname> getListLastNameFiltered() {
        return listLastNameFiltered;
    }

    public void setListLastNameFiltered(List<Lastname> listLastNameFiltered) {
        this.listLastNameFiltered = listLastNameFiltered;
    }

    public String getNewName() {
        return newName;
    }

    public void setNewName(String newName) {
        this.newName = newName;
    }
}
